<!--
 * @Author: underMoonzs 1994186472@qq.com
 * @Date: 2025-10-04 17:14:05
 * @LastEditors: underMoonzs 1994186472@qq.com
 * @LastEditTime: 2025-10-15 23:41:17
 * @FilePath: \lyshjpt\src\views\biz\jiashicang.vue
 * @Description: 领导驾驶舱
-->
<template>
  <div class="dashboard-container">
    <!-- 主体内容 -->
    <el-main class="main-content">
      <el-row :gutter="15" class="main-row">
        <!-- 左侧面板 -->
        <el-col :span="5" class="panel-col">

          <!-- 水环境质量 -->
          <div class="panel">
            <!-- <div class="panel-header">
              <h2 class="panel-title">水环境质量</h2>
            </div> -->
            <div class="panel-header">
              <div class="panel-title-container">
                <h2 class="panel-title">水环境质量</h2>
                <i class="el-icon-monitor data-icon" @click="navigateToMenu('185001', '2')"></i>
              </div>
            </div>
            <div ref="qualityPie" class="chart qualityPieChart"></div>
            <div class="warning-box">
              总数 {{ qualityPieTotal }}个，无数据 {{ qualityPieOfflinesize }}个，超标 {{ qualityPieisOvesize }}个，优良率
              {{ qualityPieexcellent }}%
            </div>
          </div>

          <div class="panel">
            <!-- <div class="panel-header">
              <h2 class="panel-title">实验室数据水质分析</h2>
              <div>{{ gaugeSampleDate }}</div>
            </div> -->
            <div class="panel-header">
              <div class="panel-title-container">
                <h2 class="panel-title">实验室数据水质分析</h2>
                <i class="el-icon-monitor data-icon" @click="navigateToMenu('185001', '1')"></i>
              </div>
            </div>
            <div class="radio-group">
              <el-radio-group v-model="manualSectionType" @change="manualTypeChange" size="small">
                <el-radio-button label="0">国考</el-radio-button>
                <el-radio-button label="1">省考</el-radio-button>
                <el-radio-button label="2">市考</el-radio-button>
              </el-radio-group>
            </div>
            <div class="water-analysis-content">
              <div ref="waterGauge" class="chart gauge-chart left-chart"></div>
              <div class="water-indicators right-indicators">
                <div class="info-text">
                  <p><strong>达标率 {{ isOver ? isOver : 0 }}%</strong> 同比 {{ tbisOver ? tbisOver : 0 }}% 环比 {{ hbisOver ?
                    hbisOver : 0 }}%</p>
                  <p><strong>优良率 {{ yl ? yl : 0 }}%</strong> 同比 {{ tbyl ? tbyl : 0 }}% 环比 {{ hbyl ? hbyl : 0 }}%</p>
                </div>
              </div>
            </div>
          </div>
          <!-- 水质变化 -->
          <div class="panel">
            <!-- <div class="panel-header">
              <h2 class="panel-title">水质变化</h2>
            </div> -->
            <div class="panel-header">
              <div class="panel-title-container">
                <h2 class="panel-title">水质变化</h2>
                <i class="el-icon-monitor data-icon" @click="navigateToMenu('185001', '1')"></i>
              </div>
            </div>
            <div ref="waterChange" class="chart"></div>
          </div>
        </el-col>

        <!-- 中间地图 -->
        <el-col :span="14" class="map-col">
          <div class="center-container">
            <div class="map-container" id="map" ref="mapContainer">
              <MapPopup :map-box="map" v-show="popupVisible" :feature-data="popupFeatureData" :layer-id="popupLayerId"
                :position="popupPosition" @close="closePopup" />
            </div>

            <!-- 图层控制 -->
            <div class="layer-control">
              <h4>图层控制</h4>
              <el-checkbox-group v-model="checkList">
                <el-checkbox v-for="layer in layerData" :label="layer.id" :key="layer.id"
                  @change="handleCheckedBoxChange">{{ layer.name }}</el-checkbox>
              </el-checkbox-group>
            </div>

            <!-- 预警弹窗 -->
            <div class="alert-popup">
              <h2 class="panel-title">报警</h2>
              <el-descriptions :column="1" border class="warn-details">
                <el-descriptions-item labelStyle="width: 80px;" v-for="(value, key) in filteredWarnProperties"
                  :key="formatLabel(key)" :label="formatLabel(key)">
                  {{ value }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <Legend2></Legend2>
          </div>

        </el-col>

        <!-- 右侧面板 -->
        <el-col :span="5" class="panel-col">
          <!-- 污染源分析 -->
          <div class="panel">
            <div class="panel-header">
              <div class="panel-title-container">
                <h2 class="panel-title">污染源分析</h2>
                <i class="el-icon-monitor data-icon" @click="navigateToMenu('185007')"></i>
              </div>
            </div>
            <div class="info-text">
              <div class="info-row">
                <p>污染源企业 32</p>
                <p>污水处理厂 {{ sewagefarmNums }}</p>
                <p>入河排污口 {{ outfallNums }}</p>
              </div>
              <div class="info-row">
                <p>排放量 {{ dischargeNums }}万吨</p>
                <p style="color: red;">超标企业 {{ overNums }}个</p>
                <p></p>
              </div>
            </div>
            <div ref="pollutionBar" class="chart"></div>

          </div>

          <!-- 实时监测列表 -->
          <div class="panel">
            <!-- <h2 class="panel-title">实时监测列表</h2> -->
            <div class="panel-header">
              <div class="panel-title-container">
                <h2 class="panel-title">实时监测列表</h2>
                <i class="el-icon-monitor data-icon" @click="navigateToMenu('185001', '2')"></i>
              </div>
            </div>
            <el-table :data="monitorList" size="small" class="monitor-table">
              <el-table-column prop="segmentname" label="名称"></el-table-column>
              <el-table-column prop="qualitylevelname" label="水质类别"></el-table-column>
              <!-- <el-table-column prop="time" label="监测时间"></el-table-column> -->
              <el-table-column prop="isoverstandard" label="是否超标">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isoverstandard === '1' ? 'danger' : 'success'" size="small">
                    {{ scope.row.isoverstandard === '1' ? '超标' : '达标' }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="waterquality" label="水质评价"></el-table-column> -->
              <el-table-column prop="overstandarddescribe" label="超标描述" width="150"></el-table-column>
              <el-table-column prop="dataSource" label="数据来源" width="150"></el-table-column>

            </el-table>
          </div>

          <div class="panel">
            <div class="panel-header">
              <div class="panel-title-container">
                <h2 class="panel-title">实时视频</h2>
                <i class="el-icon-monitor data-icon" @click="navigateToMenu('185006')"></i>
              </div>
            </div>
            <div class="warning-charts-container">
              <video class="black-video-placeholder" controls="false"></video>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-main>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';

import { XYZ } from 'ol/source';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import layerData from './utils/layerdata';

import 'ol/proj/epsg4326';
import { wmsBaseUrl } from '@/views/biz/utils/config'
import { createPointLayer, createHeatmapLayer, createWmsLayer, loadGeoJsonLayer } from '@/views/biz/utils/layerLoader';
import { getData } from '@/views/biz/utils/getJiashicangLayerData';

import { getAutoWaterQuality, getManualWaterQuality, getManualSegmentDateChange, autovaluatehourdata, getPollutionSourceAnalysis, getWarningStatistics, getWarningLastInfo } from '@/views/biz/api/jiashicang';
import Legend2 from './components/Legend2'
import MapPopup from './components/MapPopup.vue';
import { getMenuList } from "@/api/commonApi";
import { getRouterNew } from "@/api/commonApi";
export default {
  name: 'jiashicang',
  components: {
    Legend2,
    MapPopup,
  },
  data() {
    return {
      gopathMap: {
        "185001": {
          "1": "/riverGeneralMange/dataquery/manualMonitor/handdata",
          "2": "/riverGeneralMange/onlineMonitoring",
        },
        "185006": '/video/RealTimeVideo',
        "185007": '/zhManagement/wryMangement/statisticsAnalysis/company',

      },
      sectionType: 'auto',
      manualSectionType: '0',
      monitorList: [
      ],

      layerData: layerData,
      map: null,
      popupVisible: false,
      popupFeatureData: {},
      popupLayerId: '',
      popupPosition: [0, 0],
      tiandituToken: '3d9e801ed2c10bc2e6eba8037e53817b',
      currentLayerIds: [],
      loadedLayers: {},
      checkList: [],
      qualityPie: null,
      qualityPieData: [],
      qualityPieRate: {},
      qualityPieTotal: 0,
      qualityPieOfflinesize: 0,
      qualityPieisOvesize: 0,
      qualityPieexcellent: 0,
      pollutionSourceAnalysisData: null,
      PollutionDates: [],
      PollutionBarData: [],
      PollutionLineData: [],
      sewagefarmNums: 0,
      outfallNums: 0,
      overNums: 0,
      dischargeNums: 0,
      warnDataInfoIndicator: [
        { name: '地表水预警' },
        { name: '视频预警' },
        { name: '在线监测预警' }
      ],
      warnDataInfoData: [5, 20, 100],
      warnDataLevelxAxis: ['红色', '橙色', '黄色'],
      warnDataLevelxBarData: [5, 20, 100],
      warnSampleTime: '',
      totalWarnNums: 0,
      warnRedNums: 0,
      warnOrangeNums: 0,
      warnYellowNums: 0,
      isOver: 0,
      tbisOver: 0,
      hbisOver: 0,
      yl: 0,
      tbyl: 0,
      hbyl: 0,
      gaugeSampleDate: '',
      waterChangeDates: [],
      waterChangeYilei: [],
      waterChangeErlei: [],
      waterChangeSanlei: [],
      waterChangeSilei: [],
      waterChangeWulei: [],
      waterChangeLiewulei: [],
      warnProperties: {},
      warnPropertiesList: [], // 存储所有预警信息的数组
      warnPropertiesIndex: 0, // 当前显示的预警信息索引
      warnInterval: null, // 循环播放的定时器
      warnIntervalTime: 5000 // 循环播放间隔时间(毫秒)
    };
  },
  mounted() {
    this.getMenuListData()
    this.checkList = this.layerData.map(layer => layer.id);
    this.getAutoWaterQualityData();
    this.getManualWaterQualityData();
    this.getManualSegmentDateChangeData()
    this.getAutovaluatehourdata();
    this.getPollutionSourceAnalysisData();
    // this.getWarningStatisticsData();

    this.getWarningLastInfoData();
    this.initMap();

  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.warnInterval) {
      clearInterval(this.warnInterval);
    }
  },
  computed: {
    // 添加一个计算属性来过滤预警信息，只显示formatLabel有值的项
    filteredWarnProperties() {
      const filtered = {};
      for (const key in this.warnProperties) {
        if (this.formatLabel(key) !== key) {
          filtered[key] = this.warnProperties[key];
        }
      }
      return filtered;
    },
  },
  methods: {

    getMenuListData() {
      getMenuList().then((res) => {
        console.log(">>>", res);

        this.menuList = res.data;
      });
    },
    navigateToMenu(keyId, type) {
      this.$store.commit("SET_SYSID", keyId);
      this.$store.dispatch("GenerateRoutes").then(() => {
        getRouterNew(keyId).then((res) => {
          console.log(">>>luyou", res);
          let gopath = '';
          if (type) {
            gopath = this.gopathMap[keyId][type];
          } else {
            gopath = this.gopathMap[keyId];
          }
          setTimeout(() => {
            window.open(gopath, "_blank");
          }, 1000);
        });
      });
    },
    navigateToSsjc() {
      this.$router.push('/riverGeneralMange/onlineMonitoring');
    },
    navigateToSgdm() {
      this.$router.push('/riverGeneralMange/dataquery/manualMonitor/handdata');
    },

    navigateToWuranyaun() {
      this.$router.push('/zhManagement/wryMangement/statisticsAnalysis/company');
    },
    formatLabel(key) {
      // 简单的标签格式化
      const labelMap = {
        'segmentname': '报警名称',
        // 'itemname': '报警因子',
        'warnmessage': '报警信息',
        'warntime': '报警时间',
      };

      return labelMap[key] || key;
    },

    initWaterGaugeChart() {
      const waterGauge = echarts.init(this.$refs.waterGauge);
      waterGauge.setOption({
        grid: {
          // show:true,
          // left: '5%',
          // right: '5%',
          top: '5%',
          // bottom: '5%'
        },
        series: [{
          type: 'gauge',
          center: ['40%', '50%'],
          pointer: {
            icon: 'path://M2.9,0.7L2.9,0.7c1.4,0,2.6,1.2,2.6,2.6v115c0,1.4-1.2,2.6-2.6,2.6l0,0c-1.4,0-2.6-1.2-2.6-2.6V3.3C0.3,1.9,1.4,0.7,2.9,0.7z',
            width: 4,
            length: '60%',
            // offsetCenter: [0, '8%']
          },

          progress: {
            show: true
          },
          detail: {
            valueAnimation: true,
            formatter: '{value}',
            fontSize: 15,
            offsetCenter: [0, '80%']
          },
          data: [{ value: this.isOver ? this.isOver : 0, name: '达标率', }]
        }]
      });
    },
    initWaterChangeChart() {
      // 水质变化柱状图
      const waterChange = echarts.init(this.$refs.waterChange);
      waterChange.setOption({
        tooltip: { trigger: 'axis' },
        grid: {
          top: '20%',
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: { type: 'category', data: this.waterChangeDates },
        yAxis: {
          type: 'value',
          max: 100,
          min: 0,
          axisLabel: {
            formatter: '{value} %'
          }
        },
        legend: {
          data: ['I类', 'II类', 'III类', 'IV类', 'V类', '劣V类'],
          top: '0%'
        },
        series: [
          { name: 'I类', type: 'bar', stack: '总量', data: this.waterChangeYilei, itemStyle: { color: '#1e90ff' } },
          { name: 'II类', type: 'bar', stack: '总量', data: this.waterChangeErlei, itemStyle: { color: '#32cd32' } },
          { name: 'III类', type: 'bar', stack: '总量', data: this.waterChangeSanlei, itemStyle: { color: '#90ee90' } },
          { name: 'IV类', type: 'bar', stack: '总量', data: this.waterChangeSilei, itemStyle: { color: '#ffa500' } },
          { name: 'V类', type: 'bar', stack: '总量', data: this.waterChangeWulei, itemStyle: { color: '#ff6347' } },
          { name: '劣V类', type: 'bar', stack: '总量', data: this.waterChangeLiewulei, itemStyle: { color: '#dc143c' } }
        ]
      });
    },
    initPollutionChart() {
      // 污染源分析柱状图
      const pollutionBar = echarts.init(this.$refs.pollutionBar);
      pollutionBar.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: this.PollutionDates },
        yAxis: { type: 'value' },
        series: [
          { name: '超标企业', type: 'bar', data: this.PollutionBarData, itemStyle: { color: '#4a90e2' } },
          { name: '排放量', type: 'line', data: this.PollutionLineData, symbol: 'circle', lineStyle: { color: '#f74663' } }
        ]
      });
    },

    initQualityPieChart() {
      // 水环境质量饼图
      if (this.qualityPie) {
        this.qualityPie.dispose();
      }

      if (this.$refs.qualityPie) {
        try {
          this.qualityPie = echarts.init(this.$refs.qualityPie);

          // 根据 qualityPieData 生成图表数据，只保留有数据的项
          const chartData = this.qualityPieData
            .map(item => ({
              value: item.size,
              name: item.type
            }));

          // 定义颜色映射
          const colorMap = {
            'Ⅰ类': '#1e90ff',
            'Ⅱ类': '#32cd32',
            'Ⅲ类': '#90ee90',
            'Ⅳ类': '#ffa500',
            'Ⅴ类': '#ff6347',
            '劣Ⅴ类': '#dc143c',
            '无类别': '#cccccc'
          };

          // 为数据项添加颜色
          const coloredData = chartData.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: { color: colorMap[item.name] || '#666666' }
          }));
          let qualityPieRate = this.qualityPieRate;
          this.qualityPie.setOption({
            tooltip: { trigger: 'item' },
            legend: {
              show: true,
              type: 'scroll',
              orient: 'vertical',
              right: "10%",
              top: 20,
              bottom: 20,
              textStyle: {
                fontSize: 12
              },
              formatter: function (name) {
                // 在图例中显示类别名称和数值
                const dataItem = coloredData.find(item => item.name === name);
                return `${name}: ${dataItem ? dataItem.value : 0} ${qualityPieRate[name] || 0}%`;
              }
            },
            series: [{
              type: 'pie',
              radius: ['50%', '70%'],
              center: ['20%', '50%'],
              avoidLabelOverlap: false,
              label: { show: false },
              emphasis: { label: { show: true, fontSize: 14 } },
              data: coloredData
            }]
          });
        } catch (error) {
          console.error('ECharts初始化失败:', error);
        }
      }
    },
    initWarningStatisticsChart() {
      // 预警统计柱状图
      // 左侧雷达图
      const warningRadarChart = echarts.init(this.$refs.warningRadarChart);
      warningRadarChart.setOption({
        radar: {
          indicator: this.warnDataInfoIndicator
        },
        series: [{
          type: 'radar',
          data: [{
            value: this.warnDataInfoData,
            name: '预警信息'
          }]
        }]
      });

      // 右侧柱状图
      const warningBarChart = echarts.init(this.$refs.warningBarChart);
      warningBarChart.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: this.warnDataLevelxAxis },
        yAxis: { type: 'value' },
        series: [
          { name: '预警级别', type: 'bar', data: this.warnDataLevelxBarData },

        ]
      });

    },
    getAutoWaterQualityData() {
      getAutoWaterQuality().then(response => {
        if (response.code === 200) {
          this.qualityPieData = response.data || [];
          this.qualityPieData.forEach(item => {
            this.qualityPieRate[item.type] = item.rate;
          });
          //console.log("this.qualityPieData", this.qualityPieData);
          // 数据获取成功后更新图表

          this.initQualityPieChart();

        } else {
          console.error('获取水质数据失败:', response);
          this.qualityPieData = [];
        }
      }).catch(error => {
        console.error('获取水质数据异常:', error);
        this.qualityPieData = [];
      });
    },
    getManualWaterQualityData() {
      let params = { assessTypeCode: this.manualSectionType };
      getManualWaterQuality(params).then(response => {
        if (response.code === 200) {
          let data = response.data;
          this.gaugeSampleDate = data.sampleDate || '';

          let manualWaterQualityData = data.isoverList || null;
          this.isOver = manualWaterQualityData.isOver;
          this.tbisOver = manualWaterQualityData.tbisOver;
          this.hbisOver = manualWaterQualityData.hbisOver;
          this.yl = manualWaterQualityData.yl;
          this.hbyl = manualWaterQualityData.hbyl;
          this.tbyl = manualWaterQualityData.tbyl;


          this.initWaterGaugeChart();
        } else {
          console.error('获取手动断面达标数据失败:', response);
          this.manualWaterQualityData = [];
        }
      }).catch(error => {
        console.error('获取手动断面达标数据异常:', error);
        this.manualWaterQualityData = [];
      });
    },
    manualTypeChange() {
      this.getManualWaterQualityData();
    },
    getAutovaluatehourdata() {
      autovaluatehourdata().then(response => {
        if (response.code === 200) {
          this.monitorList = response.rows || [];
        } else {
          console.error('获取实时监测数据失败:', response);
          this.autovaluatehourdata = [];
        }
      }).catch(error => {
      });
    },

    getManualSegmentDateChangeData() {
      getManualSegmentDateChange().then(response => {
        if (response.code === 200) {
          let data = response.data;
          this.waterChangeDates = data.timeList || [];
          let waterChangedata = data.data || [];
          this.waterChangeYilei = [];
          this.waterChangeErlei = [];
          this.waterChangeSanlei = [];
          this.waterChangeSilei = [];
          this.waterChangeWulei = [];
          this.waterChangeLiewulei = [];
          waterChangedata.forEach(item => {
            this.waterChangeYilei.push(item.oneCategory);
            this.waterChangeErlei.push(item.twoCategory);
            this.waterChangeSanlei.push(item.threeCategory);
            this.waterChangeSilei.push(item.fourCategory);
            this.waterChangeWulei.push(item.fiveCategory);
            this.waterChangeLiewulei.push(item.sixCategory);
          })
          this.initWaterChangeChart();
        } else {
          console.error('获取手动断面日期变更数据失败:', response);
          this.manualSegmentDateChange = [];
        }
      }).catch(error => {
        console.error('获取手动断面日期变更数据异常:', error);
        this.manualSegmentDateChange = [];
      });
    },
    processPollutionSourceAnalysisData() {
      if (this.pollutionSourceAnalysisData) {
        this.sewagefarmNums = this.pollutionSourceAnalysisData.sewagefarmNums;
        this.outfallNums = this.pollutionSourceAnalysisData.outfallNums;
        this.overNums = this.pollutionSourceAnalysisData.overNums;
        this.dischargeNums = this.pollutionSourceAnalysisData.discharge;

        // 优化：合并三次遍历为一次，提高性能
        const pollutionList = this.pollutionSourceAnalysisData.pollutionList || [];
        this.PollutionDates = [];
        this.PollutionBarData = [];
        this.PollutionLineData = [];

        for (const item of pollutionList) {
          this.PollutionDates.push(item.dateTime);
          this.PollutionBarData.push(item.overNums);
          this.PollutionLineData.push(item.discharge);

        }

      }

      this.initPollutionChart();
    },
    getPollutionSourceAnalysisData() {
      getPollutionSourceAnalysis().then(response => {
        if (response.code === 200) {
          this.pollutionSourceAnalysisData = response.data;
          this.processPollutionSourceAnalysisData(); // 处理数据生成三个数组
        } else {
          console.error('获取污染源分析数据失败:', response);
          this.pollutionSourceAnalysisData = null;
        }
      }).catch(error => {
        console.error('获取污染源分析数据异常:', error);
        this.pollutionSourceAnalysisData = null;
      });
    },

    getWarningStatisticsData() {
      getWarningStatistics().then(response => {
        if (response.code === 200) {
          let warnData = response.data || [];
          let warnDataInfoList = warnData.warnDataInfoList || [];
          let warnDataLevelList = warnData.warnDataLevelList || [];
          this.totalWarnNums = warnData.totalNums;
          this.warnSampleTime = warnData.sampleTime || '';
          // 处理 warnDataInfoList 数据，生成雷达图的 indicator 和 data
          this.warnDataInfoIndicator = warnDataInfoList.map(item => ({ name: item.typeName }));
          this.warnDataInfoData = warnDataInfoList.map(item => item.nums);
          warnDataLevelList.forEach(item => {
            if (item.warnLevelName === '红色') {
              this.warnRedNums = item.number;
            } else if (item.warnLevelName === '橙色') {
              this.warnOrangeNums = item.number;
            } else if (item.warnLevelName === '黄色') {
              this.warnYellowNums = item.number;
            }
          });
          // 处理 warnDataLevelList 数据，生成 xAxis 和 barData
          this.warnDataLevelxAxis = warnDataLevelList.map(item => item.warnLevelName);
          this.warnDataLevelxBarData = warnDataLevelList.map(item => item.number);
          this.initWarningStatisticsChart();
        }
      }).catch(error => {
        console.error('获取预警统计数据异常:', error);
      });
    },
    startWarnRotation() {
      // 如果只有一条或没有预警信息，则不启动循环播放
      if (this.warnPropertiesList.length <= 1) {
        return;
      }

      // 清除之前的定时器
      if (this.warnInterval) {
        clearInterval(this.warnInterval);
      }

      // 设置定时器循环播放预警信息
      this.warnInterval = setInterval(() => {
        this.warnPropertiesIndex = (this.warnPropertiesIndex + 1) % this.warnPropertiesList.length;
        this.warnProperties = this.warnPropertiesList[this.warnPropertiesIndex];
      }, this.warnIntervalTime);
    },
    getWarningLastInfoData() {
      getWarningLastInfo().then(response => {
        if (response.code === 200) {
          let warnData = response.data || [];
          // 保存所有预警信息
          this.warnPropertiesList = warnData;

          // 如果有数据，则显示第一条
          if (warnData.length > 0) {
            this.warnProperties = warnData[0];
            this.startWarnRotation(); // 开始循环播放
          }
          //console.log("warnData", warnData);
        }
      }).catch(error => {
        console.error('获取最新预警信息异常:', error);
      });
    },


    addLayerToMap(newLayer, layerConfig) {
      newLayer.set('id', layerConfig.id);
      newLayer.set('name', layerConfig.name);
      newLayer.set('type', layerConfig.geoType);
      if ('minZoom' in layerConfig && layerConfig.minZoom) {
        newLayer.setMinZoom(layerConfig.minZoom);
      }
      if ('maxZoom' in layerConfig && layerConfig.maxZoom) {
        newLayer.setMaxZoom(layerConfig.maxZoom);
      }
      this.map.addLayer(newLayer);
      this.loadedLayers[layerConfig.id] = newLayer;
    },
    createLayer(layer) {

      return new Promise((resolve, reject) => {
        let newLayer;
        switch (layer.dataType) {
          case 'dataApi':
            getData(layer.id)
              .then(response => {
                const data = response.data || [];
                if ('heatmap' in layer && layer.heatmap) {
                  newLayer = createHeatmapLayer({
                    data: data,
                    layerId: layer.id,
                    layerType: layer.geoType
                  });
                }
                else {
                  newLayer = createPointLayer({
                    data: data,
                    layerId: layer.id,
                    layerType: layer.geoType
                  });
                }
                resolve(newLayer);
              })
              .catch(error => {
                console.error(`获取图层 ${layer.id} 数据失败:`, error);
                reject(error);
              });
            break;
          case 'wms':
            try {
              newLayer = createWmsLayer({
                url: layer.layerUrl,
                layerName: layer.wmsLayerName,
                layerId: layer.id,
                params: layer.params || {}
              });
              resolve(newLayer);
            } catch (error) {
              console.error(`创建WMS图层 ${layer.id} 失败:`, error);
              reject(new Error(`创建WMS图层失败: ${error.message}`));
            }
            break;
          case 'wmts':
            // 实现面图层创建逻辑
            console.warn('wmts图层功能尚未实现');
            reject(new Error('wmts图层功能尚未实现'));
            break;
          case 'base':
            this.switchBaseLayer(layer);
            resolve(null);
            break;
          default:
            console.error('未知图层类型:', layer.type);
            reject(new Error(`未知图层类型: ${layer.type}`));
            break;
        }
      });
    },

    removeLayer(layerId) {
      this.currentLayerIds = this.currentLayerIds.filter(id => id !== layerId);
      if (this.loadedLayers[layerId]) {
        this.map.removeLayer(this.loadedLayers[layerId]);
        delete this.loadedLayers[layerId];
      }
    },
    layerSetVisible(layerId, visible) {
      if (this.loadedLayers[layerId]) {
        this.loadedLayers[layerId].setVisible(visible);
      }
    },
    updateLayers(newLayers) {
      // 提取所有新图层的ID
      const newLayerIds = [];
      newLayers.forEach(layerid => {
        newLayerIds.push(layerid);
      });

      this.currentLayerIds.filter(id => !newLayerIds.includes(id)).forEach(id => this.removeLayer(id));
      newLayers.forEach(layerid => {

        if (!this.currentLayerIds.includes(layerid)) {
          this.currentLayerIds.push(layerid);
          layerData.filter(layer => layer.id === layerid).forEach(layer => {
            this.createLayer(layer).then((newLayer) => {
              if (newLayer) {
                this.addLayerToMap(newLayer, { ...layer });
              }
            }).catch((error) => {
              console.error(`添加图层 ${layer.id} 失败:`, error);
            });
          });

        }
      });
    },
    updateLayer(newLayer, visible) {
      layerData.filter(layer => layer.id === newLayer).forEach(layer => {
        console.log('updateLayer', layer);
        if (layer.children && layer.children.length > 0) {
          layer.children.forEach(childLayer => {
            if (this.loadedLayers[childLayer.id]) {
              this.layerSetVisible(childLayer.id, visible);
            }
            else {
              this.createLayer(childLayer).then((l) => {
                if (l) {
                  this.addLayerToMap(l, { ...childLayer });
                }
              }).catch((error) => {
                console.error(`添加图层 ${childLayer.id} 失败:`, error);
              });
            }

          })
        }

        else {
          if (this.loadedLayers[newLayer]) {
            this.layerSetVisible(newLayer, visible);
          }
          else {
            this.createLayer(layer).then((newLayer) => {
              if (newLayer) {
                this.addLayerToMap(newLayer, { ...layer });
              }
            }).catch((error) => {
              console.error(`添加图层 ${layer.id} 失败:`, error);
            });
          }

        }
      })


    },
    handleCheckedLayerChange(node, visible) {
      this.updateLayers(checkedLayers);
    },
    handleCheckedBoxChange(visible, node) {
      this.updateLayer(node.target.value, visible)
    },

    registerMapEvents() {
      // 使用箭头函数保持this指向正确
      this.moveEndListener = () => {
        const currentResolution = this.map.getView().getResolution();
        console.log('当前分辨率:', currentResolution);
      };

      this.map.on('moveend', this.moveEndListener);
    },
    // 弹窗相关方法
    showPopup(featureData, layerId, position) {

      this.popupFeatureData = featureData;
      this.popupLayerId = layerId;
      // this.popupLayerType = layerType;
      this.popupPosition = position;
      this.popupVisible = true;
    },

    closePopup() {

      this.popupFeatureData = {};
      this.popupLayerId = '';
      this.popupLayerType = '';
      this.popupVisible = false;
    },
    registerMapClick() {
      this.map.on('singleclick', (evt) => {
        const coordinate = evt.coordinate;
        const features = [];
        this.map.forEachFeatureAtPixel(evt.pixel, (feature) => {
          features.push(feature);
        });

        // 如果找到了要素，则可以进一步处理
        if (features.length > 0) {
          // 处理获取到的要素
          const feature = features[0];
          // 获取要素属性
          const featureData = feature.getProperties();

          // 获取图层信息
          const layerId = feature ? feature.get('layerId') : '';



          // 计算弹窗位置
          // const geometry = feature.getGeometry();
          // const coordinate = geometry.getType() === 'Point'
          //   ? geometry.getCoordinates()
          //   : getCenter(geometry.getExtent());

          // const pixel = this.map.getPixelFromCoordinate(coordinate);

          // 显示弹窗
          this.showPopup(featureData, layerId, coordinate);
        } else {

          this.closePopup();
        }
      });
    },
    initMap() {
      let base_layer = createWmsLayer({
        url: wmsBaseUrl,
        layerName: 'gp:base_dlg',
        layerId: 'base_dlg',
        params: {
          "format": 'image/png',
          'VERSION': '1.1.1',
          "STYLES": '',
          "LAYERS": 'gp:base_dlg',
        }
      });
      this.map = new Map({
        target: 'map',
        // controls: [new ScaleLine()],
        layers: [
          new TileLayer({
            name: 'tianditu-vec',
            source: new XYZ({
              url: `http://t{0-7}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.tiandituToken}`,
              projection: 'EPSG:4326',
              tileGrid: new WMTSTileGrid({
                origin: [-180, 90],
                resolutions: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625],
                matrixIds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
              })
            })
          }),
          new TileLayer({
            name: 'tianditu-cva',
            source: new XYZ({
              url: `http://t{0-7}.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.tiandituToken}`,
              projection: 'EPSG:4326',
              tileGrid: new WMTSTileGrid({
                origin: [-180, 90],
                resolutions: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625],
                matrixIds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
              })
            })
          }),
          base_layer
        ],
        view: new View({
          projection: 'EPSG:4326',
          center: [112.930691, 35.791355],
          zoom: 11,
          maxZoom: 18,
          minZoom: 1
        })
      });

      this.checkList.forEach(item => {
        this.updateLayer(item, true)
      });
      this.registerMapClick();

    },
  },

};
</script>
<style scoped>
/* ===== 布局样式 ===== */
.dashboard-container {
  height: calc(100vh - 105px);
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.main-content {
  padding: 0;
  flex: 1;
  overflow: hidden;
}

.main-row {
  height: 100%;
}



/* ===== 面板布局样式 ===== */
.panel-col {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.map-col {
  height: 100%;
}

.panel {
  background: white;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.panel-title {
  font-size: 16px;
  margin: 0 0 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.panel-header .panel-title {
  margin: 0;
  border: none;
  padding: 0;
}

.panel-header .btn-group {
  margin-bottom: 0;
}

/* ===== 图表容器样式 ===== */
.chart {
  height: 200px;
}

.gauge-chart {
  height: 220px;
}

.monitor-table {
  height: 250px;
}

.warning-charts-container {
  display: flex;
  flex-direction: row;
}

.half-chart {
  flex: 1;
  height: 200px;
}

/* ===== 控件样式 ===== */
.btn-group,
.radio-group {
  margin-bottom: 10px;
}

/* ===== 信息展示样式 ===== */
.warning-box {
  background: #fff9e6;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 10px;
}

.info-text {
  font-size: 12px;
  line-height: 1.6;
  color: #555;
}

/* 污染源分析信息分行显示 */
.info-row {
  display: flex;
  justify-content: flex-start;
}

.info-row p {
  margin: 0;
  flex: 1;
  padding: 0 5px;
  text-align: left;
}

.info-row p:first-child {
  padding-left: 0;
}

/* ===== 地图相关样式 ===== */
.center-container {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.map-container {
  flex: 1;
  background: #eef2f7;
  border-radius: 8px;
  min-height: 0;
  /* 允许flex子项收缩到内容高度以下 */
}

.layer-control {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: white;
  padding: 10px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  width: 180px;
}

.alert-popup {
  position: absolute;
  top: 20px;
  right: 20px;
  background: white;
  padding: 10px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  width: 350px;
  font-size: 12px;
  color: #333;
}

.alert-popup h3 {
  margin: 0 0 5px;
  color: #d00;
}

/* 固定预警信息标签宽度 */
.warn-details {
  gap: 10px;
}

/* 水质分析面板左右布局 - 7:3 宽度比例 */
.water-analysis-content {
  display: flex;
  flex-direction: row;
}

.left-chart {
  flex: 6;
  min-width: 0;
}

.right-indicators {
  flex: 4;
  min-width: 0;
  display: flex;
  align-items: center;
  /* padding-left: 20px; */
}

/* 添加新的样式 */
.panel-title-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.data-icon {
  cursor: pointer;
  font-size: 18px;
  color: #409EFF;
  transition: all 0.3s;
}

.data-icon:hover {
  color: #66b1ff;
  transform: scale(1.1);
}

/* .monitor-table {
  height: 230px;
} */

/* ===== 响应式优化 ===== */
@media (max-width: 1200px) {
  .panel-col {
    flex-direction: column;
  }

  .water-analysis-content {
    flex-direction: column;
  }

  .left-chart,
  .right-indicators {
    flex: 1;
  }

  .right-indicators {
    padding-left: 0;
    padding-top: 10px;
  }
}

.black-video-placeholder {
  background-color: #000;
  width: 100%;
  height: 200px;
  border-radius: 4px;
  object-fit: cover;
}

@media (max-width: 992px) {
  .main-row {
    flex-direction: column;
  }

  .panel-col,
  .map-col {
    width: 100% !important;
    max-width: 100%;
  }

  .center-container {
    margin-top: 15px;
  }

}
</style>
